package service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import model.AttributeDefinition;
import utils.DatabaseManager;
import utils.DBUtil;
import constant.AttributeDataType;

/**
 * 属性服务类，提供属性相关的数据库操作
 */
public class AttributeService {
    
    /**
     * 获取所有属性定义
     * @return 属性定义列表
     */
    public static List<AttributeDefinition> getAllAttributes() {
        List<AttributeDefinition> attributes = new ArrayList<>();
        
        try (Connection conn = DBUtil.connect();
             PreparedStatement stmt = conn.prepareStatement("SELECT attribute_id, attribute_key, display_name, data_type, default_value FROM attributes WHERE is_delete = '1' ORDER BY attribute_id");
             ResultSet rs = stmt.executeQuery()) {
            
            while (rs.next()) {
                AttributeDefinition attr = new AttributeDefinition();
                attr.setAttributeId(rs.getInt("attribute_id"));
                attr.setAttributeKey(rs.getString("attribute_key"));
                attr.setDisplayName(rs.getString("display_name"));
                attr.setDataType(AttributeDataType.fromValue(rs.getInt("data_type")));
                attr.setDefaultValue(rs.getString("default_value"));
                attributes.add(attr);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return attributes;
    }
    
    /**
     * 添加新的属性定义
     * @param attribute 属性定义对象
     * @return 新增属性的ID，失败返回-1
     */
    public static int addAttribute(AttributeDefinition attribute) {
        String sql = "INSERT INTO attributes (attribute_key, display_name, data_type, default_value, is_delete) VALUES (?, ?, ?, ?, '1')";
        
        try (Connection conn = DBUtil.connect();
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            
            pstmt.setString(1, attribute.getAttributeKey());
            pstmt.setString(2, attribute.getDisplayName());
            pstmt.setInt(3, AttributeDataType.STRING.getValue());
            pstmt.setString(4, attribute.getDefaultValue());
            
            int affectedRows = pstmt.executeUpdate();
            
            if (affectedRows == 0) {
                return -1;
            }
            
            try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    return generatedKeys.getInt(1);
                } else {
                    return -1;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }
    
    /**
     * 更新属性定义
     * @param attribute 属性定义对象
     * @return 更新是否成功
     */
    public static boolean updateAttribute(AttributeDefinition attribute) {
        String sql = "UPDATE attributes SET attribute_key = ?, display_name = ?, data_type = ?, default_value = ? WHERE attribute_id = ?";
        
        try (Connection conn = DBUtil.connect();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, attribute.getAttributeKey());
            pstmt.setString(2, attribute.getDisplayName());
            pstmt.setInt(3, attribute.getDataType().getValue());
            pstmt.setString(4, attribute.getDefaultValue());
            pstmt.setInt(5, attribute.getAttributeId());
            
            int affectedRows = pstmt.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 删除属性定义
     * @param attributeId 属性ID
     * @return 删除是否成功
     */
    public static boolean deleteAttribute(int attributeId) {
        String sql = "DELETE FROM attributes WHERE attribute_id = ?";
        
        try (Connection conn = DBUtil.connect();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setInt(1, attributeId);
            
            int affectedRows = pstmt.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 根据ID获取属性定义
     * @param attributeId 属性ID
     * @return 属性定义对象，如果不存在则返回null
     */
    public static AttributeDefinition getAttributeById(int attributeId) {
        String sql = "SELECT attribute_id, attribute_key, display_name, data_type, default_value FROM attributes WHERE attribute_id = ? AND is_delete = '1'";
        
        try (Connection conn = DBUtil.connect();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setInt(1, attributeId);
            
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    AttributeDefinition attr = new AttributeDefinition();
                    attr.setAttributeId(rs.getInt("attribute_id"));
                    attr.setAttributeKey(rs.getString("attribute_key"));
                    attr.setDisplayName(rs.getString("display_name"));
                    attr.setDataType(AttributeDataType.fromValue(rs.getInt("data_type")));
                    attr.setDefaultValue(rs.getString("default_value"));
                    return attr;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return null;
    }
    
    /**
     * 根据显示名称获取属性定义
     * @param displayName 属性显示名称
     * @return 属性定义对象，如果不存在则返回null
     */
    public static AttributeDefinition getAttributeByDisplayName(String displayName) {
        String sql = "SELECT attribute_id, attribute_key, display_name, data_type, default_value FROM attributes WHERE display_name = ? AND is_delete = '1'";
        
        try (Connection conn = DBUtil.connect();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, displayName);
            
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    AttributeDefinition attr = new AttributeDefinition();
                    attr.setAttributeId(rs.getInt("attribute_id"));
                    attr.setAttributeKey(rs.getString("attribute_key"));
                    attr.setDisplayName(rs.getString("display_name"));
                    attr.setDataType(AttributeDataType.fromValue(rs.getInt("data_type")));
                    attr.setDefaultValue(rs.getString("default_value"));
                    return attr;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return null;
    }
} 